<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/15
 * Time: 16:12
 */

namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Queue;
use app\common\model\OrderRefund as orf;
use app\api\model\OrderRefund as ore; 
use app\api\model\Toexcel as te;
class Crontab extends Controller
{
    //定时任务
    public function crontab()
    {
        //处理景点的时间
        $res = Db::name('tour_order')->where('is_del', 0)->where('order_status', 1)->select();
        if ($res) {
            foreach ($res as $k => $v) {
                if (time() > $v['ticket_date']) {
                    Db::name('tour_order')->where('order_id', $v['order_id'])->setField('order_status', 7);
                }
            }
        }

        //酒店的订单
        $hotel = Db::name('hotel_order')->where('is_del', 0)->where('order_status', 1)->select();
        $hotel_refund = Db::name('order_refund')->field('order_sn')->where('object_type', 4)->select();
        if ($hotel) {
            foreach ($hotel as $key => $value) {
                if (time() > $value['start_time']) {
                    $have = $this->deep_in_array($value['order_sn'], $hotel_refund);
                    if ($have) {

                    }else{
                        Db::name('hotel_order')->where('order_id', $value['order_id'])->setField('order_status', 7);
                    }
                }
            }
        }

        //旅行社的订单
        $team = Db::name('gtour_order')->where('is_del', 0)->where('order_status', 1)->select();
        if ($team) {
            foreach ($team as $key => $value) {
                if (time() > $value['gtour_start']) {
                    Db::name('gtour_order')->where('order_id', $value['order_id'])->setField('order_status', 7);
                }
            }
        }

    }

    //代付款处理
    public function d_order()
    {
        //处理景点的时间
        $res = Db::name('tour_order')->where('is_del', 0)->where('order_status', 0)->select();
        if ($res) {
            foreach ($res as $k => $v) {
                if (time() > $v['ticket_date']) {
                    Db::name('tour_order')->where('order_id', $v['order_id'])->setField('order_status', 2);
                }
            }
        }
        //酒店的订单
        $hotel = Db::name('hotel_order')->where('is_del', 0)->where('order_status', 0)->select();
        if ($hotel) {
            foreach ($hotel as $key => $value) {
                if (time() > $value['start_time']) {
                    Db::name('hotel_order')->where('order_id', $value['order_id'])->setField('order_status', 2);
                }
            }
        }

        //旅行社的订单
        $team = Db::name('gtour_order')->where('is_del', 0)->where('order_status', 0)->select();
        if ($team) {
            foreach ($team as $key => $value) {
                if (time() > $value['gtour_start']) {
                    Db::name('gtour_order')->where('order_id', $value['order_id'])->setField('order_status', 2);
                }
            }
        }
    }

    //循环插入消息队列退款
    public function t_order()
    {
        //查询
        $time = Db::name('jlou_goods')->where('is_del', 0)->where('is_display', 1)->select();

        foreach ($time as $k => $v) {
            if (time() > strtotime($v['time'])) {

                if ($v['shop_min_num'] > $v['number']) {
                    $order = Db::name('jlou_order')->where('goods_id', $v['id'])->select();
                    foreach ($order as $key => $value) {
                        if ($value['order_status'] == 1 && $value['is_refund'] != 1) {
                            Db::startTrans();
                            try {
                                $jobHandlerClassName = 'app\api\job\Jlou';
                                // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                                $jobQueueName = "jlou";
                                // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
                                //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
                                $jobData = [
                                    'uid' => $value['uid'],
                                    'order_id' => $value['order_id'],
                                    'order_sn' => $value['order_sn'],
                                    'order_price' => $value['order_price'],
                                    'pay_type' => $value['pay_type'],

                                ];
                                // 4.将该任务推送到消息队列，等待对应的消费者去执行
                                $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                                // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
                                if ($isPushed !== false) {
                                    echo '成功';
                                    Db::commit();
                                } else {
                                    echo '失败';
                                    Db::rollback();
                                }
                            } catch (\Exception $e) {
                                Db::rollback();
                            }

                        }

                    }
                }
            }
        }
    }

    /**
     * 每天早晨8点取消已过期的景点订单*
     */
    public function canceltourorder()
    {

        $orf = new orf();
        //查询为待出行,已经过期了的订单
        $tourWaitOrderList = Db::name('tour_order')
            ->alias("o")
            ->field('o.tour_id as shop_id,o.user_id as uid,o.order_status,ticket_date,o.pay_type,o.order_id,t.sale_sum,o.order_sn,o.order_price,o.type_id')
            ->join('tours t', 'o.tour_id=t.tour_id', 'left')
            ->where(['o.order_status' => 1, 'o.ticket_date' => ['<', time()]])
            ->select();

        Db::startTrans();
        try {
            if (count($tourWaitOrderList) > 0) {
                $data['order_status'] = 5;
                $data['cancel_id'] = 3;
                $data['is_refund'] = 1;
                foreach ($tourWaitOrderList as $key => $value) {
                    $obj['order_sn'] = $value['order_sn'];
                    $obj['order_price'] = $value['order_price'];
                    $obj['user_id'] = $value['uid'];
                    $obj['object_id'] = $value['shop_id'];
                    //如果过期了商户的状态  // 景点
                    $obj['refund_reason'] = "景点用户申请退款";
                    $obj['object_type'] = 4;
                    $value['refund_reason'] = "景点用户申请退款";
                    $payType = $value['pay_type'];//1支付宝 2微信
                    if ($payType == 1) {
                        $rs = $orf->aliRefund($value);
                    }
                    if ($payType == 2) {
                        $rs = $orf->weixinRefund($value);
                    }
                    if ($rs == 'SUCCESS') {
                        $obj['refund_status'] = 1;
                        Db::name('tours')
                            ->where('tour_id', $value['shop_id'])
                            ->setDec('sale_sum', 1);
                        Db::name('tour_order')
                            ->where('order_id', $value['order_id'])
                            ->update($data);
                    } else {
                        return apiReturn('400', '退款失败', 0);
                    }
                    //新增订单日志
                    $logOrder['order_id'] = $value['order_id'];
                    $logOrder['order_status'] = 5;
                    $logOrder['log_content'] = "用户取消订单";
                    $logOrder['user_id'] = $value['uid'];
                    $logOrder['create_time'] = time();
                    $logOrder['order_type'] = 1;
                    Db::name('log_orders')->insert($logOrder);
                    //记录到退款记录表
                    $orderRefund = new ore();
                    $orderRefund->addOrderRefund($obj);
                    Db::commit();
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    public function deep_in_array($value, $array) {

        foreach($array as $item) {
            if(!is_array($item)) {
                if ($item == $value) {
                    return true;
                } else {
                    continue;
                }
            }

            if(in_array($value, $item)) {
                return true;
            } else if($this->deep_in_array($value, $item)) {
                return true;
            }
        }
        return false;
    }
      public function Generate(){ 
        //判断下一次的结算时间是否和当前的时间相等
   $nowdata = date('Y-m-d',time()); 
    //查询出到结算时间的酒店
     $hotelList = Db::name('hotel')
    ->field("settlement_date,hotel_id,settled_day")
    ->where(['is_del'=>0,'is_pass'=>1,'is_rest'=>0,'is_display'=>0,'settled_day'=>['neq',0],'settlement_date'=>$nowdata])
    ->select();
    if(count($hotelList)>0){ 
      $hotelwhere['settlement_id']=0;
      $hotelwhere['order_status'] = ['IN',[3,4]];
      $type = 1;
      $hotelwhere['is_del']=0;
      foreach ($hotelList as $key => $value) {
         
         $hotelwhere['hotel_id']=$value['hotel_id']; 
          //计算出当前酒店的结算订单
         $hotelNoSettlementList =Db::name('hotel_order')->where($hotelwhere)->select(); 
         if(count($hotelNoSettlementList)>0){  
             $settlementMoney = 0;
             $commissionFee = 0;
             $ids = [];
             foreach ($hotelNoSettlementList as $key => $v) {
                 $ids[] = $v['order_id']; 
                 $settlementMoney += $v['order_price']; 
                 $commissionFee += abs($v['commission_fee']);
             }
            $this->jiesuan($value['hotel_id'],$settlementMoney,$commissionFee,$type,$ids);
              $days = $value['settled_day'];
              $settlement_date = date("Y-m-d",strtotime("+$days day"));
            //修改下一次的结算时间
             Db::name('hotel')
                ->where('hotel_id',$value['hotel_id'])
                ->update(['last_settlement_date'=>date('Y-m-d',time()),'settlement_date'=>$settlement_date]);
         }
         
      }  
    } 
    //生成景点的结算
     $tourList = Db::name('tours')
    ->field('settlement_date,tour_id,settled_day')
    ->where(['is_del'=>0,'is_display'=>0,'is_pass'=>1,'settled_day'=>['neq',0],'settlement_date'=>$nowdata])
    ->select();   
    if(count($tourList)>0){  
      $type = 2; 
      $tourwhere['settlement_id']=0;
      $tourwhere['order_status'] = ['IN',[3,4]];
      $tourwhere['is_del']=0;
      foreach ($tourList as $key => $value) { 
         $tourwhere['tour_id']=$value['tour_id'];
          //计算出当前酒店的结算订单
         $tourNoSettlementList =Db::name('tour_order')->where($tourwhere)->select(); 
         if(count($tourNoSettlementList)>0){ 
             $settlementMoney = 0;
             $commissionFee = 0;
             $ids = [];
             foreach ($tourNoSettlementList as $key => $v) {
                 $ids[] = $v['order_id']; 
                 $settlementMoney += $v['order_price']; 
                 $commissionFee += abs($v['commission_fee']);
             }
            $this->jiesuan($value['tour_id'],$settlementMoney,$commissionFee,$type,$ids);
             $days = $value['settled_day'];
             $settlement_date = date("Y-m-d",strtotime("+$days day"));
             //修改下一次的结算时间
             Db::name('tours')
                ->where('tour_id',$value['tour_id'])
                ->update(['last_settlement_date'=>date('Y-m-d',time()),'settlement_date'=>$settlement_date]);
         }
        
      } 

    }
    //生成旅行社的结算订单
    //计算出旅行社到期需要结算的商家
    $teamList = Db::name('team')
    ->field('settlement_date,team_id,settled_day')
    ->where(['is_del'=>0,'is_display'=>0,'is_pass'=>1,'settled_day'=>['neq',0],'settlement_date'=>$nowdata])
    ->select();
    if(count($teamList)>0){ 
      $type = 3;  
      $gtwhere['settlement_id']=0;
      $gtwhere['order_status'] = ['IN',[3,4]]; 
      $gtwhere['is_del']=0;
      foreach ($teamList as $key => $value) { 
         $gtwhere['team_id']=$value['team_id'];
          //计算出当前酒店的结算订单
         $teamNoSettlementList =Db::name('gtour_order')->where($gtwhere)->select();   
        if(count($teamNoSettlementList)>0){  
             $settlementMoney = 0;
             $commissionFee = 0;
             $ids = [];
             foreach ($teamNoSettlementList as $key => $v) {
                 $ids[] = $v['order_id']; 
                 $settlementMoney += $v['order_price']; 
                 $commissionFee += abs($v['commission_fee']);
             }
            $this->jiesuan($value['team_id'],$settlementMoney,$commissionFee,$type,$ids);
            $days = $value['settled_day'];
            $settlement_date = date("Y-m-d",strtotime("+$days day"));
            //修改下一次的结算时间
             Db::name('team')
                ->where('team_id',$value['team_id'])
                ->update(['last_settlement_date'=>date('Y-m-d',time()),'settlement_date'=>$settlement_date]);
         }
        
      } 
    }

 }

   public function jiesuan($id,$settlementMoney,$commissionFee,$type,$ids){  
     //生成结算订单
       Db::startTrans();
         try{ 
             $data['settlement_type'] = 1;
             $data['object_id'] =  $id;
             $data['object_type'] = $type;
             $data['settlement_money'] = $settlementMoney; //商品总金额
             $data['commission_fee'] = $commissionFee; //结算应收的佣金
             $data['back_money'] = $settlementMoney-$commissionFee; //返回给商户的钱
             $data['settlement_status'] = 1;
             $data['settlement_time'] = time(); 
             $data['admin_id'] = 0;//自动结算
             $settlementId = Db::name('settlements')->insertGetId($data);
             if($settlementId){
                //生成结算表 
              if($type == 1){
                //修改商家订单情况
               Db::name("hotel_order")
               ->where(['order_id'=>['in',$ids]])
               ->update(['settlement_id'=>$settlementId]);  
               //修改商家的未结算的订单数和未结算佣金数 
              $up['no_settled_order_num'] = 0;  
              $num_count = count($ids); 
              Db::name('hotel')->where('hotel_id',$id)->setDec("no_settled_order_num",$num_count); 
              if(!empty($commissionFee)){
               Db::name('hotel')->where('hotel_id',$id)->setDec("no_settled_order_fee",$commissionFee);  
               }
              }elseif($type == 2){ 
                //修改商家订单情况
                 Db::name("tour_order")
                 ->where(['order_id'=>['in',$ids]])
                 ->update(['settlement_id'=>$settlementId]);  
                 //修改商家的未结算的订单数和未结算佣金数 
                $up['no_settled_order_num'] = 0;  
                $num_count = count($ids); 
                Db::name('tours')->where('tour_id',$id)->setDec("no_settled_order_num",$num_count); 
                if(!empty($commissionFee)){
                 Db::name('tours')->where('tour_id',$id)->setDec("no_settled_order_fee",$commissionFee);  
               }

              }elseif($type == 3){ 
                //修改商家订单情况
                 Db::name("gtour_order")
                 ->where(['order_id'=>['in',$ids]])
                 ->update(['settlement_id'=>$settlementId]);  
                 //修改商家的未结算的订单数和未结算佣金数 
                $up['no_settled_order_num'] = 0;  
                $num_count = count($ids); 
                Db::name('team')->where('team_id',$id)->setDec("no_settled_order_num",$num_count); 
                if(!empty($commissionFee)){
                 Db::name('team')->where('team_id',$id)->setDec("no_settled_order_fee",$commissionFee);  
               }    
              }  
                $toexcel = new te();
                $settlementForm =  $toexcel->daochu($settlementId); 
                $settlementNo = $settlementId.(fmod($settlementId,7));
                Db::name('settlements')
                ->where('settlement_id',$settlementId)
                ->update(['settlement_no'=>$settlementNo,'settlement_form'=>$settlementForm]);
               
             } 
              Db::commit(); 
           return 1;  
         }catch(\Exception $e){ 
            Db::rollback(); 
            return 0; 
         }
         return 0;
   }
}